package com.siyoumi.app.modules.account.admin;

import com.siyoumi.app.entity.SysDepartment;
import com.siyoumi.app.modules.account.entity.VaSysDepartment;
import com.siyoumi.app.modules.account.service.SvcDepartment;
import com.siyoumi.component.http.InputData;
import com.siyoumi.component.http.XHttpContext;
import com.siyoumi.exception.EnumSys;
import com.siyoumi.mybatispuls.JoinWrapperPlus;
import com.siyoumi.util.XReturn;
import com.siyoumi.validator.XValidator;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/xadmin/account/account__depertment__edit")
public class account__depertment__edit
        extends AccountController {
    @GetMapping()
    public XReturn index() {
        setPageTitle("部门-编辑");

        List<String> pathMap = new ArrayList<>();
        Map<String, Object> data = new HashMap<>();
        data.put("dep_order", 0);
        if (isAdminEdit()) {
            SysDepartment entity = SvcDepartment.getApp().loadEntity(getID());

            HashMap<String, Object> dataAppend = new HashMap<>();
            dataAppend.put("id", entity.getKey());

            //合并
            data = entity.toMap();
            data.putAll(dataAppend);
        }
        getR().setData("data", data);

        return getR();
    }


    @PostMapping("/save")
    public XReturn save(@Validated VaSysDepartment vo, BindingResult result) {
        if (!isSuperAdmin()) {
            return EnumSys.ADMIN_AUTH_SUPER_ERR.getR();
        }
        //自定义验证
        //name
        {
            JoinWrapperPlus<SysDepartment> query = SvcDepartment.getApp().join();
            query.eq("dep_x_id", XHttpContext.getX())
                    .eq("dep_name", vo.getDep_name());
            if (isAdminEdit()) {
                query.ne(SvcDepartment.getApp().fdKey(), getID());
            }
            if (SvcDepartment.getApp().first(query) != null) {
                result.addError(XValidator.getErr("dep_name", "帐号已存在"));
            }
        }

        //统一验证
        XValidator.getResult(result);

        InputData inputData = InputData.fromRequest();
        return SvcDepartment.getBean().edit(inputData, vo);
    }
}
